import { router } from '@/router';
import { getUploadUrl } from '@/utils/env';
import { useAuthStore } from '@/state/modules/auth';
/**
 * 跳转
 * @param name 路由名称
 * @param params 参数
 * @param tabBar 是否tabBar
 * @param redirect 是否关闭当前页
 */
export function handleJump(name: string, params: Record<string, any> = {}, tabBar = false, redirect = false) {
    if (tabBar === true) {
        router.replaceAll({ name: name, params });
    } else {
        if (redirect === true) {
            router.replace({ name: name, params });
        } else {
            router.push({ name: name, params });
        }
    }
}
/**
 * 返回上一页
 * @param timeout
 */
export function goBack(timeout = 500) {
    setTimeout(() => {
        router.back();
    }, timeout);
}

/**
 * 富文本处理
 * @param html
 * @returns
 */
export function formatRichText(html: string) {
    let newContent = html.replace(/<img[^>]*>/gi, function (match) {
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (match) {
        match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
        return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    // eslint-disable-next-line no-useless-escape
    newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
    return newContent;
}

// 图片处理-选择图片
export function chooseMedia(count = 1, mediaType?: ('image' | 'video' | 'mix')[] | undefined) {
    return new Promise((resolve, reject) => {
        uni.chooseMedia({
            mediaType: mediaType,
            count: count, //默认9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album'], //从相册选择
            success: (res) => {
                resolve(res.tempFiles);
            },
            fail: (err) => {
                reject(err);
            },
        });
    });
}
/**
 * 上传
 * @param url
 * @returns
 */
export function uploadFiels(url: string) {
    console.log(getUploadUrl());
    const uploadUrl = getUploadUrl();
    uni.showLoading({
        title: '上传中',
    });

    return new Promise((resolve, reject) => {
        const authStore = useAuthStore();
        uni.uploadFile({
            url: uploadUrl,
            filePath: url,
            name: 'file',
            header: { token: authStore.getToken },
            success: (res) => {
                const data = JSON.parse(res.data);
                if (data.code === 1) {
                    uni.hideLoading();
                    resolve(data.data);
                } else {
                    uni.hideLoading();
                    uni.showModal({
                        title: '上传失败',
                        content: data.msg,
                    });
                    reject(res);
                }
            },
            fail: (err) => {
                reject(err);
            },
        });
    });
}

// 打电话
export function callPhone(phoneNumber = '') {
    const num = phoneNumber.toString();
    uni.makePhoneCall({
        phoneNumber: num,
        fail(err) {
            console.log('makePhoneCall出错', err);
        },
    });
}

export function previewImage(urls: string[]) {
    uni.previewImage({
        urls: urls,
    });
}

export function download(url) {
    const downloadTask = uni.downloadFile({
        url: url, //仅为示例，并非真实接口地址。
        success: (res) => {
            if (res.statusCode === 200) {
                console.log('下载成功');
            }
            uni.getFileSystemManager().saveFile({
                tempFilePath: res.tempFilePath,
                success: function (red) {
                    console.log(red);
                    uni.showModal({
                        title: '提示',
                        content: '文件已保存：' + red.savedFilePath,
                        cancelText: '我知道了',
                        confirmText: '打开文件',
                        success: function (result) {
                            if (result.confirm) {
                                uni.openDocument({
                                    filePath: red.savedFilePath,
                                    success: () => {
                                        console.log('成功打开');
                                    },
                                });
                            }
                        },
                    });
                },
                fail: function (err) {
                    console.log(err);
                },
            });
        },
        complete: () => {},
    });
    downloadTask.onProgressUpdate((res) => {
        console.log('下载进度' + res.progress);
        console.log('已经下载的数据长度' + res.totalBytesWritten);
        console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);

        // // 满足测试条件，取消下载任务。
        // if (res.progress > 50) {
        // 	downloadTask.abort();
        // }
    });
}
// 订阅消息按钮
export function SubscriptionMessage(tmplIds = []) {
    // 获取小程序订阅状态
    uni.getSetting({
        withSubscriptions: true,
        success: function (res) {
            if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
                // 调起消息订阅界面
                uni.showModal({
                    title: '提示',
                    content: '请授权开通服务通知',
                    showCancel: true,
                    success: function (ress) {
                        if (ress.confirm) {
                            // 调起消息订阅界面
                            uni.requestSubscribeMessage({
                                tmplIds: tmplIds,
                                success(res) {
                                    console.log('订阅消息 成功 ');
                                    console.log(res);
                                },
                                fail(err) {
                                    console.log('订阅消息 失败 ');
                                    console.log(err);
                                },
                            });
                        }
                    },
                });
            } else {
                console.log('订阅消息未开启');
                uni.showToast({
                    title: '订阅消息未开启',
                    icon: 'error',
                    duration: 2000,
                });
            }
        },
    });
}
